//
//  ChargeMoneyVC.m
//  ImGuider
//
//  Created by 李陆涛 on 2018/1/2.
//  Copyright © 2018年 imguider. All rights reserved.
//

#import "ChargeMoneyVC.h"
#import "WebViewVC.h"
#import "WXAlertVC.h"
#import "ChargeMoneyCCell.h"

#import "ChargeDetailVC.h"
#import "IAPManager.h"

@interface ChargeMoneyVC () <UICollectionViewDelegate, UICollectionViewDataSource,UICollectionViewDelegateFlowLayout, UIScrollViewDelegate>
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *scrollViewH;
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *collectionViewH;

@property (weak, nonatomic) IBOutlet UILabel *balanceLabel;

@property (weak, nonatomic) IBOutlet YYLabel *chargeIntroLabel;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *chargeLabelH;

@property (weak, nonatomic) IBOutlet UIView *headView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *headviewTop;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *headViewH;

@property (weak, nonatomic) IBOutlet UIButton *payBtn;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomViewBottom;

@property (weak, nonatomic) IBOutlet UILabel *chargeInfoDesLabel;
@property (weak, nonatomic) IBOutlet UILabel *balanceDesLabel;
@property (weak, nonatomic) IBOutlet UIButton *recordBtn;


@property (nonatomic) NSInteger selectRow;

@property (nonatomic, strong) NSArray *dataSource;

@end

@implementation ChargeMoneyVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
//    [self setNavThemeGradient];
    self.customBarStyle = UIStatusBarStyleLightContent;
    
    self.payBtn.backgroundColor = kThemeColor;
    
    self.chargeInfoDesLabel.text = MYLocalizedString(@"COIN_TOPUP_INFO", nil);
    self.balanceDesLabel.text = MYLocalizedString(@"COIN_BALANCE", nil);
    
    self.chargeInfoDesLabel.textColor = kSubitleColor;
    
    [self.recordBtn setTitle:MYLocalizedString(@"COIN_TOPUP_RECORD", nil) forState:UIControlStateNormal];
    
    
    self.title = MYLocalizedString(@"ACCOUNT_WALLET", nil);
    self.barBGAlpha = 0;

    [self closeAutomaticallyAdjustsScrollViewInsets:self.scrollView];
    self.bottomViewBottom.constant = kBottomHeight;
    self.headViewH.constant = kScreenWidth * 9 / 16;
    
    CGFloat height = (kScreenWidth - 65) / 3.0 * 0.7;
    
    CGFloat collectionViewH = 40 + 16 * 2 + height * 2;
    self.collectionViewH.constant = collectionViewH;
    
    self.chargeIntroLabel.attributedText = [self getYYLabelAttributedText];
    self.chargeIntroLabel.numberOfLines = 0;
    self.chargeIntroLabel.font = Font(14);
    
    CGFloat chargerInfoH = [self.chargeIntroLabel sizeThatFits:CGSizeMake(kScreenWidth - 32, MAXFLOAT)].height;
    self.chargeLabelH.constant = chargerInfoH;
    
    self.scrollViewH.constant = kScreenWidth * 9 / 16 + collectionViewH + chargerInfoH + 52.5 + 32 + 16 + 8;
    [self reloadBalance];
    
    
    [ActivityIndicatorView showHUDAddedTo:self.view backgroundColor:[UIColor whiteColor]];
    
    @weakify(self);
    [NetAPIManager getPaylistBlock:^(NSArray<ChargeCoinModel *> *paylistArray, NSError *error) {
        
        @strongify(self);
        [ActivityIndicatorView hideHUDAddedTo:self.view];
        self.dataSource = paylistArray;
        self.selectRow = 0;
        [self.collectionView reloadData];
    }];
}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
    [[UIApplication sharedApplication] setIdleTimerDisabled:YES];

}

- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
    [[UIApplication sharedApplication] setIdleTimerDisabled:NO];
}

- (void)reloadBalance {
    
    self.balanceLabel.text = [NSString stringWithFormat:@"%@ %@",@([UserManager sharedManager].user.coin).stringValue,MYLocalizedString(@"PUBLIC_COIN_NAME", nil)];
}

- (void)setSelectRow:(NSInteger)selectRow {
    
    _selectRow = selectRow;
    
    ChargeCoinModel *model = self.dataSource[selectRow];
    
    [self.payBtn setTitle:[NSString stringWithFormat:@"%@ %@",MYLocalizedString(@"COIN_PAY_NOW", nil),model.name] forState:UIControlStateNormal];
}

/** 获取富文本 */
- (NSAttributedString *)getYYLabelAttributedText {

    NSString *textString = MYLocalizedString(@"COIN_PAY_INFO", nil);
    NSMutableAttributedString *mutableAttributedString = [[NSMutableAttributedString alloc] initWithString:textString];
    mutableAttributedString.font = Font(14);
    mutableAttributedString.color = kContentColor;
    mutableAttributedString.lineSpacing = 8;
    
    NSRange range1 = [textString rangeOfString:MYLocalizedString(@"PAYORDER_HELP_DESHighlight", nil)];
    
    [mutableAttributedString setColor:kThemeColor range:range1];
    
    YYTextHighlight *stepHighlight = [YYTextHighlight highlightWithBackgroundColor:kBGColor];
    [mutableAttributedString setTextHighlight:stepHighlight range:range1];
    
    stepHighlight.tapAction = ^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
        
        WebViewVC *webVC = [WebViewVC new];
        webVC.url = @"https://mp.weixin.qq.com/s/y58rnOQSlMFHSNGuDdKdQQ";
        webVC.title = MYLocalizedString(@"PAYORDER_HELP_DESHighlight", nil);
        [self.navigationController pushViewController:webVC animated:YES];
    };
    
    
    NSRange range2 = [textString rangeOfString:@"ImGuider"];
    [mutableAttributedString setColor:kThemeColor range:range2];
    
    YYTextHighlight *IGHighlight = [YYTextHighlight highlightWithBackgroundColor:kBGColor];
    [mutableAttributedString setTextHighlight:IGHighlight range:range2];
    
    IGHighlight.tapAction = ^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
        
        UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
        [pasteboard setString:@"ImGuider"];
        
        WXAlertVC *alertVC = [WXAlertVC new];
        
        [alertVC showWithVC:self];
    };
    
    return mutableAttributedString;
}
- (IBAction)showChargeDetail:(id)sender {
    
    ChargeDetailVC *detailVC = [ChargeDetailVC new];
    [self.navigationController pushViewController:detailVC animated:YES];
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    
    return [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"headview" forIndexPath:indexPath];
}

- (nonnull __kindof UICollectionViewCell *)collectionView:(nonnull UICollectionView *)collectionView cellForItemAtIndexPath:(nonnull NSIndexPath *)indexPath {
    
    ChargeCoinModel *coinModel = self.dataSource[indexPath.row];
    
    ChargeMoneyCCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ChargeMoneyCCell" forIndexPath:indexPath];
    cell.isSelect = (indexPath.row == self.selectRow ? YES : NO);
    
    cell.coinModel = coinModel;
    
    
    return cell;
}

- (NSInteger)collectionView:(nonnull UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.dataSource.count;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    CGFloat width = (kScreenWidth - 65) / 3.0;
    
    return CGSizeMake(width, width * 0.7);
}


- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    if (self.selectRow == indexPath.row) {
        return;
    }
    
    self.selectRow = indexPath.row;
    [self.collectionView reloadData];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    if (scrollView != self.scrollView) {
        return;
    }
    
    CGFloat offset = scrollView.contentOffset.y;
    
    if (offset >= (CGRectGetMaxY(self.balanceLabel.frame) - kNavigationBarHeight)) {
        
        self.barBGAlpha = (offset - (CGRectGetMaxY(self.balanceLabel.frame) - kNavigationBarHeight)) / kNavigationBarHeight;
        self.customBarStyle = UIStatusBarStyleDefault;
    } else {
        self.barBGAlpha = 0;
        self.customBarStyle = UIStatusBarStyleLightContent;
    }
    
    if (offset < 0) {
        self.headViewH.constant = kScreenWidth * 9 / 16 - offset;
        self.headviewTop.constant = offset;
    } else {
        self.headViewH.constant = kScreenWidth * 9 / 16;
        self.headviewTop.constant = 0;
    }
}
- (IBAction)payAction:(id)sender {
    
    if (self.dataSource.count <= self.selectRow) {
        return;
    }
    
    ChargeCoinModel *model = self.dataSource[self.selectRow];
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    @weakify(self);
    
    [[IAPManager sharedManager] paymentID:model.appleid couponid:nil payType:PayTypeIAP ordernumber:nil merchType:MerchTypeTopup andBlock:^(NSString *result, NSError *error) {
        @strongify(self);
        
        
        if (!error) {
            [IGUtil showToast:MYLocalizedString(@"PAYORDER_SUCCESS", nil)];
            
            [NetAPIManager getUserInfoWithBlock:^(NSString *result, NSError *error) {
                
                [MBProgressHUD hideHUDForView:self.view animated:YES];
                [self reloadBalance];
                [[NSNotificationCenter defaultCenter] postNotificationName:kRefreshUserNotif object:nil];
                
                [self.navigationController popViewControllerAnimated:YES];
            }];
            
            return ;
        }
        
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        
        if (error.code == PAY_FILEDCOED_SERVERERROR) {
            
            [IGAlertView alertWithTitle:MYLocalizedString(@"PAYORDER_FAILED_TITLE", nil) message:MYLocalizedString(@"PAYORDER_FAILED_CONTENT", nil) cancelButtonTitle:MYLocalizedString(@"PUBLIC_CANCEL", nil) commitBtn:MYLocalizedString(@"MYORDER_CONTACTSTAFF", nil) commit:^{
                UIViewController *contactService = [IGUtil loadViewController:@"ContactService" storyboard:@"Account"];
                [self.navigationController pushViewController:contactService animated:YES];
            } cancel:nil];
            
        } else {
            
            [IGUtil showToast:[IGUtil tipFromError:error]];
        }
    }];
}

@end
